package com.ekuaitu.kuaitu.map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.bean.BikeAroundBean;
import com.ekuaitu.kuaitu.bean.FenceData;
import com.ekuaitu.kuaitu.bean.ParkBean;
import com.ekuaitu.kuaitu.utils.DensityUtils;
import com.ekuaitu.kuaitu.utils.MyApplication;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Michael Pi on 2016/8/27.
 */
public class MarkerUtils {

    private Context mContext;
    private AMap aMap;
    private Bitmap bitmap;

    public MarkerUtils() {
    }


    public MarkerUtils(Context mContext, AMap aMap) {
        this.mContext = mContext;
        this.aMap = aMap;
    }

    /**
     * 更新定位图标
     *
     * @param curPosition
     * @return
     */
    public Marker addLocationIcon(LatLng curPosition) {
        Marker marker = aMap.addMarker(new MarkerOptions().position(curPosition).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon)).anchor(0.5f, 0.5f));
        marker.setZIndex(2);   //定位2，有奖单车1.5，普通单车1  商家1.7
        return marker;
    }


    /**
     * 添加多个单车marker
     */

    public ArrayList<Marker> addBikeMarkersToMap(AMap aMap, List<BikeAroundBean.AttachmentBean.BikesBean> bikesResult) {
        ArrayList<MarkerOptions> markerOptionList = new ArrayList<>();
        Bitmap redBitMap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.marker_directional_bike);
        Bitmap originalBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.marker_bike);
        for (BikeAroundBean.AttachmentBean.BikesBean bikeInfo : bikesResult) {
            MarkerOptions markerOptions = new MarkerOptions();
            if (bikeInfo.getIsRedPackage() == 1) {  //红包
                markerOptions
                        .position(new LatLng(bikeInfo.getLatitude(), bikeInfo.getLongitude()))
                        .icon(BitmapDescriptorFactory.fromBitmap(redBitMap))
                        .title("")
                        .setFlat(true);
            } else {
                markerOptions
                        .position(new LatLng(bikeInfo.getLatitude(), bikeInfo.getLongitude()))
                        .icon(BitmapDescriptorFactory.fromBitmap(originalBitmap))
                        .title("")
                        .setFlat(true);
            }
            markerOptionList.add(markerOptions);
        }
        redBitMap.recycle();
        originalBitmap.recycle();
        ArrayList<Marker> markerList = aMap.addMarkers(markerOptionList, false);
        //marker添加parkId

        for (int j = 0; j < bikesResult.size(); j++) {
            Marker marker = markerList.get(j);
            Map<String, String> markerInfo = new HashMap<>();
            markerInfo.put("bikeId", bikesResult.get(j).getBikeId() + "");
            markerInfo.put("bikePrice", bikesResult.get(j).getPrice() + "");
            markerInfo.put("lockType", bikesResult.get(j).getLockType() + "");
            markerInfo.put("bikeLicense", bikesResult.get(j).getLicenseTag() + "");
            markerInfo.put("isRedBike", bikesResult.get(j).getIsRedPackage() + "");
            marker.setObject(markerInfo);
            Animation animation = new ScaleAnimation(0, 1, 0, 1);
            animation.setInterpolator(new LinearInterpolator());
            //整个移动所需要的时间
            animation.setDuration(300);
            //设置动画
            marker.setAnimation(animation);
            if (bikesResult.get(j).getIsRedPackage() == 1) { //红包
                marker.setZIndex(1.5f);
            } else {
                marker.setZIndex(1);
            }
            //开始动画
            marker.startAnimation();
        }
        return markerList;
    }


    /**
     * 添加一个单车marker
     *
     * @param longitude
     * @param latitude
     */

    public Marker addOneRedBikeMarkerToMap(double latitude, double longitude) {
        return aMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude))
                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.marker_red_bike)))
                .setFlat(true));

    }


    private OnBrandMarkerAddedListener onBrandMarkerAdded;

    /**
     * 添加商家的marker
     *
     * @param longitude
     * @param latitude
     */
    public void addBrandMarkerToMap(final String latitude, final String longitude, final String brand, final String picId, @Nullable final OnBrandMarkerAddedListener onBrandMarkerAddedListener) {
        this.onBrandMarkerAdded = onBrandMarkerAddedListener;
        final View view = View.inflate(mContext, R.layout.brand_marker, null);
        final ImageView imageView = (ImageView) view.findViewById(R.id.brand_image);
        final TextView textView = (TextView) view.findViewById(R.id.brand_text);
        Log.i("brandPic", MyApplication.getInstance().getImageUrl() + picId);
        Glide.with(mContext)
                .load(MyApplication.getInstance().getImageUrl() + picId)
                .centerCrop()
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        //在这里添加一些图片加载完成的操作
                        imageView.setImageDrawable(resource);
                        textView.setText(brand);
                        Marker marker = aMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)))
                                .icon(BitmapDescriptorFactory.fromBitmap(convertViewToBitmap(view)))
                                .setFlat(true));
                        marker.setZIndex(1.7f);
                        if (onBrandMarkerAddedListener != null) {
                            onBrandMarkerAddedListener.onBrandMarkerAdded(marker);    //将接收到的结果传递至MainActivity
                        }
                        return false;
                    }

                })
                .into(imageView);

    }

    public interface OnBrandMarkerAddedListener {
        void onBrandMarkerAdded(Marker marker);
    }

    //view转化为图片的方法，网上类似的方法有很多
    public static Bitmap convertViewToBitmap(View view) {
        view.setDrawingCacheEnabled(true);
        view.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0,
                view.getMeasuredWidth(),
                view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap cacheBitmap = view.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        return bitmap;
    }

    /**
     * 添加电动车marker
     */

    public ArrayList<Marker> addCarMarkersToMap(AMap aMap, List<ParkBean.AttachmentBean.ParksBean> areasResult) {
        ArrayList<MarkerOptions> markerOptionList = new ArrayList<MarkerOptions>();
        for (int i = 0; i < areasResult.size(); i++) {
            //创建park图标
            bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.marker_park).copy(Bitmap.Config.ARGB_8888, true);
            Canvas canvas = new Canvas(bitmap);
            TextPaint textPaint = new TextPaint();
            textPaint.setAntiAlias(true);
            textPaint.setTextAlign(Paint.Align.CENTER);
            textPaint.setTextSize(DensityUtils.sp2px(mContext, 15f));
            textPaint.setColor(mContext.getResources().getColor(R.color.colorPrimary));
            canvas.drawText(areasResult.get(i).getAvailableCar() + "", (float) 0.5 * bitmap.getWidth(), (float) 0.5 * bitmap.getHeight(), textPaint);// 设置bitmap上面的文字位置
            //设置marker
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions
                    .position(new LatLng(areasResult.get(i).getLatitude(), areasResult.get(i).getLongitude()))
                    .icon(BitmapDescriptorFactory.fromBitmap(bitmap)).setFlat(true);
            markerOptionList.add(markerOptions);
            bitmap.recycle();
        }
        ArrayList<Marker> markerList = aMap.addMarkers(markerOptionList, false);
        //给marker添加parkId等数据
        for (int j = 0; j < markerList.size(); j++) {
            Map<String, String> markerInfo = new HashMap<>();
            markerInfo.put("parkId", areasResult.get(j).getId() + "");
            markerInfo.put("parkName", areasResult.get(j).getLocationName());
            if (areasResult.get(j).getLocationName() != null) {
                Marker marker = markerList.get(j);
                marker.setObject(markerInfo);
                Animation animation = new ScaleAnimation(0, 1, 0, 1);
                animation.setInterpolator(new LinearInterpolator());
                //整个移动所需要的时间
                animation.setDuration(300);
                //设置动画
                marker.setZIndex(1);
                marker.setAnimation(animation);
                //开始动画
                marker.startAnimation();
            }
        }
        return markerList;
    }

    /**
     * 添加行行驶中电动车marker
     */
    public ArrayList<Marker> addRedCarMarkersToMap(AMap aMap, List<FenceData.ParkFence> areasResult) {
        ArrayList<MarkerOptions> markerOptionList = new ArrayList<MarkerOptions>();
        for (int i = 0; i < areasResult.size(); i++) {
            //创建park图标
            bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.wangdian).copy(Bitmap.Config.ARGB_8888, true);
            Canvas canvas = new Canvas(bitmap);
            TextPaint textPaint = new TextPaint();
            textPaint.setAntiAlias(true);
            textPaint.setTextAlign(Paint.Align.CENTER);
            textPaint.setTextSize(DensityUtils.sp2px(mContext, 15f));
            textPaint.setColor(mContext.getResources().getColor(R.color.colorPrimary));
            //canvas.drawText("网点", (float) 0.5 * bitmap.getWidth(), (float) 0.5 * bitmap.getHeight(), textPaint);// 设置bitmap上面的文字位置
            //设置marker
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions
                    .position(new LatLng(areasResult.get(i).getCenterLatitude(), areasResult.get(i).getCenterLongitude()))
                    .icon(BitmapDescriptorFactory.fromBitmap(bitmap)).setFlat(true);
            markerOptionList.add(markerOptions);
            bitmap.recycle();
        }
        ArrayList<Marker> markerList = aMap.addMarkers(markerOptionList, false);
        //给marker添加parkId等数据
        for (int j = 0; j < markerList.size(); j++) {
            Map<String, String> markerInfo = new HashMap<>();
            markerInfo.put("parkId", areasResult.get(j).getParkId() + "");
            markerInfo.put("parkName", areasResult.get(j).getName());
            if (areasResult.get(j).getName() != null) {
                Marker marker = markerList.get(j);
                marker.setObject(markerInfo);
                Animation animation = new ScaleAnimation(0, 1, 0, 1);
                animation.setInterpolator(new LinearInterpolator());
                //整个移动所需要的时间
                animation.setDuration(300);
                marker.setZIndex(1);
                //设置动画

                marker.setAnimation(animation);
                //开始动画
                marker.startAnimation();
            }
        }
        return markerList;
    }


    /**
     * 添加一个汽车marker
     *
     * @param longitude
     * @param latitude
     */
    public Marker addCarMarkerToMap(double latitude, double longitude) {
        Marker marker = aMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude))
                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.marker_car)))
                .setFlat(true));
        Animation animation = new ScaleAnimation(0, 1, 0, 1);
        animation.setInterpolator(new LinearInterpolator());
        //整个移动所需要的时间
        animation.setDuration(300);
        marker.setZIndex(1);
        //设置动画
        marker.setAnimation(animation);
        //开始动画
        marker.startAnimation();
        return marker;
    }


}
